package com.woniuxy.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.annotation.MyLog;
import com.woniuxy.annotation.RequirePermission;
import com.woniuxy.config.properties.UploadProperties;
import com.woniuxy.entity.User;
import com.woniuxy.service.user.FileService;
import com.woniuxy.service.user.UserService;
import com.woniuxy.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@EnableConfigurationProperties(UploadProperties.class)
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;

    @Autowired
    private UploadProperties uploadProperties;

    @RequirePermission("user:find")
    @PostMapping("user/findOne")
    public ResultVo findOne(@RequestBody String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new RuntimeException("userId is required");
        }
        User user = userService.findOne(Integer.valueOf(userId));
        return ResultVo.success(user);
    }

    @RequirePermission("user:find")
    @PostMapping("user/findLike")
    public ResultVo findLike(@RequestBody String str) {
        System.out.println(str);
        str = "%" + str + "%";
        List<User> user = userService.Like(str);
        return user != null ? ResultVo.success("ok", user) : ResultVo.failure("no");
    }

    @RequirePermission("user:find")
    @PostMapping("user/findAll")
    public ResultVo findAll0() {
        List<User> user = userService.findAll();
        return user.size() > 0 ? ResultVo.success("ok", user) : ResultVo.failure("no");
    }

    @RequirePermission("user:find")
    @PostMapping("user/findByPage")
    public ResultVo findByPage(@RequestBody Map<String, String> map) {
        String strPage = map.remove("page");
        String strSize = map.remove("size");
        PageInfo<User> user = userService.findByPage(Integer.valueOf(strPage), Integer.valueOf(strSize));
        return ResultVo.success(user);
    }

    @MyLog("删除用户")
    @RequirePermission("user:delete")
    @PostMapping("user/delete")
    public ResultVo delete(@RequestBody String userId, HttpServletRequest request) {
        if (!StringUtils.hasText(userId)) {
            throw new RuntimeException("userId is required");
        }

        deleteUserPhotoByUserId(Integer.valueOf(userId), request);

        int rows = userService.delete(Integer.valueOf(userId));

        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    private void deleteUserPhotoByUserId(Integer userId, HttpServletRequest request) {
        User target = userService.findOne(Integer.valueOf(userId));
        String realPath = request.getServletContext().getRealPath("/images");
        fileService.delete(realPath + "/" + target.getUserPhoto());
    }

    @MyLog("修改用户信息")
    @RequirePermission("user:update")
    @PostMapping("user/update")
    public ResultVo updateOne0(@RequestBody User user, HttpServletRequest request) {

        deleteUserPhotoByUserId(user.getUserId(), request);
        int rows = userService.updateOne(user);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @MyLog("添加用户")
    @RequirePermission("user:save")
    @PostMapping("user/save")
    public ResultVo save(@RequestBody User user) {
        int rows = userService.save(user);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @MyLog("修改用户信息")
    @RequirePermission("user:update")
    @PostMapping("user/upload")
    public ResultVo upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String dir = request.getServletContext().getRealPath("/" + uploadProperties.getDir());

        log.debug("文件上传路径:{}", dir);

        String newFileName = fileService.upload(file, dir);

        Map<String, String> map = new HashMap<>();

        String url = uploadProperties.getUrl() + "/" + newFileName;

        map.put("url", url);

        map.put("newFileName", newFileName);

        return ResultVo.success(map);
    }

//    @RequirePermission("user:distRoleToUser")
    @MyLog("给用户分配角色")
    @RequirePermission("role:update")
    @PostMapping("user/distRoleToUser")
    public ResultVo distRoleToUser(@RequestBody Map map) {
        Integer userId = (Integer) map.remove("userId");
        List<Integer> roleIds = (List<Integer>) map.remove("roleIds");
        int rows = userService.distRoleToUser(userId, roleIds);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

}
